import axios from 'axios'

axios.defaults.baseURL = 'http://119.8.32.3:9080/blog/'
const service = axios.create({
  baseURL: 'http://119.8.32.3:9080/blog/',
  timeout: 60000
})

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) config.headers['token'] = token
    config.headers['behavior'] = '1'
    return config
  },
  error => {
    window.console.error('ajaxError', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const showMesIfError = response.config.showMesIfError
    if (showMesIfError && Number(response.data.code) !== 200) {
      alert(response.data.mes)
      return Promise.reject(response.data.mes)
    }
    if (!showMesIfError && Number(response.data.code) !== 200) {
      return Promise.reject()
    }
    return response.data.data
  },
  error => {
    alert(error.message)
    return Promise.reject(error)
  }
)

export default service
